package com.fsx.consumer.controller;


import com.fsx.consumer.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 订单 服务的调用方
 */
@RestController
@RequestMapping("/order")
public class OderController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/goods/{id}")
    public Goods finGoodsById(@PathVariable int id) {
        // 远程调用 goods 服务中的 findOneById 接口
        // String url = "http://localhost:8000/goods/findOneById/" + id; // 写死了 不好

        // 改为动态获取
        // 1. 注入 DiscoveryClient 对象
        // 2. 调用

        List<ServiceInstance> instances = discoveryClient.getInstances("EUREKA-PROVIDER");
        if (instances == null || instances.size() == 0) {
            // 集合没有数据
            return null;
        }
        ServiceInstance serviceInstance = instances.get(0);
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        Goods goods = restTemplate.getForObject("http://" + host + ":" + port + "/goods/findOneById/"+id, Goods.class);
        return goods;
    }
}
